package com.wisdytech.common.shiro;

import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.log.model.SysLog;
import com.wisdytech.linkdcs.log.service.ISysLogService;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.util.PatternMatcher;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 请求过滤器 过滤请求保存日志
 *
 * @author dlb
 * @since 2018年4月11日16:35:43
 */
public class SystemLogFilter extends PathMatchingFilter {

    private static final Logger logger = LoggerFactory.getLogger(SystemLogFilter.class);

    @Autowired
    private ISysLogService sysLogService;

    @Autowired
    private IUserService userService;


    /**
     * url拦截，记录用户访问以及操作日志
     */
    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        //logger.info(">>>>>>>>>>>>>>>>记录日志<<<<<<<<<<<<<<<<<<< ");
        //SysUser sysUser =(SysUser)SecurityUtils.getSubject().getPrincipal();
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isBlank(username)) {
            return super.onPreHandle(request, response, mappedValue);
        }
        //登录成功，写入session
        SysUser sysUser = userService.getSystemUserByNameExcludeResources(username);
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        String url = httpServletRequest.getRequestURI();
        String contextPath = httpServletRequest.getContextPath();
        //截取url,getRequestURI方法获取的url带上下文,需要截取掉
        url = url.substring(contextPath.length());
        //logger.info(">>>>>>>>>>>>>>当前请求路径url:{},请求人:{}<<<<<<<<<<<<<<<<<<",url,sysUser.getUsername());
        PatternMatcher matcher = new AntPathMatcher();
        SysLog log = new SysLog();
        log.setPkId(BaseUtil.getUUID());
        log.setCreateDate(new Date());
        log.setRouteIp(BaseUtil.getIpAddress(httpServletRequest));
        log.setUserId(sysUser.getPkId());
        log.setUserName(sysUser.getTruename());
        //记录访问日志 根据ant路径匹配
        if (matcher.matches("/**/index", url)) {
            //根据url记录用户最后访问模块名称，不记录数据库，直接写到内存中
            //session.setAttribute("moduleName", sysLogService.getModuldeName(url));
            log.setType("0");
            sysLogService.add(log, url.substring(1));
        }
        //记录操作日志
        if (matcher.matches("/**/*.mvc", url)) {
            log.setType("1");
            sysLogService.addUserOperateLog(log, url.substring(1));
        }
        return super.onPreHandle(request, response, mappedValue);
    }


}
